<h3>JSONP方法封装</h3>

<input type="text" name="name"> 姓名
<input type="text" name="age"> 年龄
<input type="button" value="提交">
<hr>
<span id="name">你的姓名是 :</span>
<span id="age">你的年龄是 :</span>
<hr>
<img src="/img/ajax/ajax_jsonp_packging.png" alt="">


<script>
    function Jsonp({
        url = null,
        data = null,
        response
    }) {
        let str = data && Object.keys(data).map(key => `${key}=${data[key]}`).join('&');
        url += `?callback=response${!str?'':`&${str}`}`
        let script = document.createElement('script');
             script.src = url;
             
             $('body').append(script).find(script).remove()       
            window.response = response;
    }
    $('[type="button"]').on('click', function() {
        let name = $('[name="name"]').val()
        let age = $('[name="age"]').val()
        Jsonp({
            url: 'http://api.hyfarsight.com/jsonp',
            data: {
                name,
                age
            },
            response(res) {
              $('#name').html('你的姓名是:' + res.name)
              $('#age').html('你的年龄是:' +res.age)
            }
        })
    })
</script>